﻿using MoetutuServer.Helper;
using MoetutuServer.Helper.PublishHelper;
using MoetutuServer.PublishHelper;
using MoetutuServer.WebSite.Pixiv;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MoetutuServer.WebSite.Huaban
{
    class HuabanScanner
    {
        public static void Start()
        {
            FileHelper.FloderExits(HuabanStaticValue.LogFloderPath,true);
            FileHelper.FileExits(HuabanStaticValue.LogFilePath, true);
            String Shtml = WebHelper.HttpGet(HuabanStaticValue.ImgApi, HuabanStaticValue.HuabanHeader());

            AnalysisJson(Shtml);
        }

        private static void AnalysisJson(string Shtml)
        {
            try
            {

                Huaban.HuabanStaticValue.HuabanListJson.Root AllJson = JsonConvert.DeserializeObject<Huaban.HuabanStaticValue.HuabanListJson.Root>(Shtml);
                foreach (HuabanStaticValue.HuabanListJson.PinsItem Single in AllJson.pins)
                {
                    if (!JudgeComplete())
                        break;

                    if (HuabanHelper.JudgeQualified(Single))
                        continue;

                    String Link = Single.link;
                    Console.WriteLine(Link);
                    int ImgID = TextHelper.StringToInt(TextHelper.RegexText(Link, "illust_id=[0-9]{0,}").Replace("illust_id=", ""));
                    Console.WriteLine(ImgID);
                    if (ImgID != 0)
                    {
                        if (PixivHelper.ReflushLog(ImgID))//如果没下载过就不跳出。
                            continue;

                        string ImgLink = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + ImgID;
                        StartPost(ImgLink, Single, ImgID);
                    }
               
                }

            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            JudgeComplete(true);
        }
        /// <summary>
        /// 判断是否需要继续，如果继续返回true
        /// </summary>
        /// <param name="StartFlag"></param>
        /// <returns></returns>
        private static bool JudgeComplete(bool StartFlag=false)
        {
            List<string> TempLogCount = FileHelper.ReadAllLine(HuabanStaticValue.LogFilePath);
            Console.WriteLine("当前已发布{0}个", TempLogCount.Count);
            if (TempLogCount.Count < 40)
            {

                if (StartFlag)
                {
                    int SleepTime = 600;
                    Console.WriteLine("未达到预设数量，休眠{0}秒后继续。{1}",SleepTime,DateTime.Now.ToString());
                    Thread.Sleep(SleepTime*1000);
                    Console.WriteLine("休眠结束"+ DateTime.Now.ToString());
                    Start();

                }
                return true;
            }
            else {
                Console.WriteLine("已超出预设数量，结束。");
                return false;
            }
        }




        /// <summary>
        /// 启动解析并且发布
        /// </summary>
        /// <param name="PageLiink"></param>
        private static void StartPost(string PageLiink, HuabanStaticValue.HuabanListJson.PinsItem Single,int ImgID)
        {
            string Shtml = WebHelper.HttpGet(PageLiink);
            int Score = TextHelper.StringToInt(HtmlHelper.GetFirstValue(HtmlHelper.GetTextValueList(Shtml, "//section[@class='score']/ul/li[2]/span[2]")));
            String ImgLink = HtmlHelper.GetFirstValue(HtmlHelper.GetImgSrcVlaueList(Shtml, "//a[@class='require-register medium-image  _work ']/img"));
            string UserID = HtmlHelper.GetFirstValue(HtmlHelper.GetLinkVlaueList(Shtml, "//h2[@class='name']/a")).Replace("member.php?id=", "");
            string NewTag = string.Format("PID({0})", ImgID);
            List<string> TagList = HtmlHelper.GetTextValueList(Shtml, "//ul[@class='inline-list']/li/a[2]");
            Console.WriteLine("图片链接" + ImgLink + "用户ID" + UserID + "评分:" + Score);
            if (StaticValue.ExcludeKey.Contains(UserID)) {
                Console.WriteLine("画师需要屏蔽");
                return;
            }
            if (ImgLink == "")///未捕获到图片连接的情况
            {
                Console.WriteLine("未捕获到图片链接");
                return;
            }
            //https://i.pximg.net/c/240x480/img-master/img/2017/12/01/00/00/01/66106157_p0_master1200.jpg
            //https://i.pximg.net/c/600x600/img-master/img/2017/12/01/20/58/56/661158_p0_master1200.jpg
          
          
         
            if (HuabanHelper. PixivJudge(NewTag, TagList))
                return;

     //       TagList.Add(NewTag);//加入日志flag这个标签
          //  TagList.Add("Pixiv Id " + UserID);
            TagList = Helper.PublishHelper.TagHelper.TagShort(TagList);
            if (ImgLink != "" && Score > 1000)
            {
                Console.WriteLine("可以发布");
                String HuabanImg = "https://hbimg.b0.upaiyun.com/" + Single.file.key;
                Console.WriteLine(HuabanImg);
                String Imgurl = HuabanHelper. GetImg("https://i.pximg.net/img-original" + TextHelper.RegexText(ImgLink, "/img/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/") + ImgID+ "_p0");
                Console.WriteLine(Imgurl);

              
                List<String> ImgList = UploadImg.GetPicBed(Imgurl, "Pixiv");
                ImgList.Add(HuabanImg);
                if (ImgList.Count >= 2)
                {
                    List<String> TagListTemp = WebSite.Pixiv.TagHelper.TranslateTag(TagList);//首先进行一次汉化处理

                  
                    string Content = CreateContent.EstablishContent(TagListTemp, ImgList)+
                        string.Format("<a class='pixivImgid'>{0}</a>", NewTag)+
                        string.Format("<a class='pixivArtid'>{0}</a>", "Pixiv Id " + UserID);
                    string Title = CreateTitle.Title(TagList);
                 


                    PostHelper.WordPressPostHelper.Publish(StaticValue.PostUser, Title, Content, TagListTemp, ImgLink.Replace("c/600x600", "c/240x480"), new List<int>() { 1 });
                }


                FileHelper.AppendUTF8Text(HuabanStaticValue.LogFilePath, "");

            }
        }


    }
}
